package com.wyu.blog.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wyu.blog.dto.RespDTO;
import com.wyu.blog.entity.*;
import com.wyu.blog.service.ArticleService;
import com.wyu.blog.service.CollectService;
import com.wyu.blog.service.UserFriendService;
import com.wyu.blog.service.UserService;
import com.wyu.blog.util.BlogUtil;
import com.wyu.blog.util.RecommendUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;



@Controller
public class MainController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserFriendService userFriendService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private CollectService collectService;

    private String url = "http://192.168.18.1:8081/img/";

    /**
     * 找到推荐文章的标题
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public List<Article> recommend(User user){
        List<Collect> collArticle = collectService.findCollectByUserId(user.getUserId());
        List<Collect> notCollArticle = collectService.findNotCollect(user.getUserId());
        ArrayList collList = new ArrayList();
        ArrayList notCollList = new ArrayList();
        ArrayList list = new ArrayList();
        for(Collect collect : collArticle){
            collList.add(collect.getArticle().getArticleTitle());
        }
        for(Collect notCollect : notCollArticle) {
            notCollList.add(notCollect.getArticle().getArticleTitle());
        }
        for(int i = 0; i < collList.size(); i++){
            for(int j = 0; j < notCollList.size(); j++) {
                float n = RecommendUtil.levenshtein(collList.get(i).toString(), notCollList.get(j).toString());
                Map tempMap = new HashMap();
                tempMap.put("name",notCollList.get(j));
                tempMap.put("number",n);
                list.add(tempMap);
            }
        }

        Collections.sort(list, new Comparator<Map<String, Object>>(){

            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                Float num1 =(Float)o1.get("number");//name1是从你list里面拿出来的一个
                Float num2= (Float)o2.get("number"); //name1是从你list里面拿出来的第二个name
                return -num1.compareTo(num2);
            }

        });

        List newList = list.subList(0,5);
        List nameList = new ArrayList();
        List<Article> recommendArticle = new ArrayList<>();
        for(int i = 0;i < newList.size();i++)
        {
            Map<String,Object> maps = (Map<String, Object>) newList.get(i);
            String name = maps.get("name").toString();
            nameList.add(name);
            Article article = articleService.findArticleByTitle(name);
            recommendArticle.add(article);

        }

        return recommendArticle;
    }

    /**
     * 博客主页
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @GetMapping(value = "/main")
    public String main(Model model, HttpSession session){

        User user = (User)session.getAttribute("loginUser");
        List<Article> topArticle = articleService.findTopArticle();
        List<Article> hotArticle = articleService.findHotArticle();
        List<Article> recentArticle = articleService.findRecentArticle();
        model.addAttribute("topArticle",topArticle);
        model.addAttribute("hotArticle",hotArticle);
        model.addAttribute("recentArticle",recentArticle);

        if(user != null) {
            List<Collect> collArticle = collectService.findCollectByUserId(user.getUserId());
            if(!collArticle.isEmpty()) {
                List<Article> recommendArticle = recommend(user);
                model.addAttribute("recommendArticle", recommendArticle);
            }else{
                model.addAttribute("recommendArticle", null);
            }
        }
        return "main";
    }

    /**
     * 错误页
     * @return
     */
    @GetMapping(value = "/error")
    public String error(){
        return "error";
    }

    /*
        博客后台页面
     */
    @GetMapping(value = "/manager/user")
    public String userManager(){
        return "admin/user";
    }

    @GetMapping(value = "/manager/article")
    public String articleManager(){
        return "admin/article";
    }

    @GetMapping(value = "/manager/category")
    public String categoryManager(){
        return "admin/category";
    }

    @GetMapping(value = "/manager/comment")
    public String commentManager(){
        return "admin/comment";
    }



    /**
     * 搜索页
     */
    @GetMapping(value = "/search")
    public String search(){
        return "search";
    }

    /**
     * 模糊查询文章
     */
    @RequestMapping(value = "/search/article")
    public String searchArticle(Model model,@RequestParam("articleName") String articleName,
                    @RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum){
        PageHelper.startPage(pageNum,5);
        if(!("".equals(articleName))) {
            List<Article> articles = articleService.findArticleByLike(articleName);
            Integer articleNumber = articleService.findArticleNumByLike(articleName);
            PageInfo<Article> pageInfo = new PageInfo<>(articles);
            model.addAttribute("pageInfo",pageInfo);
            model.addAttribute("articles", articles);
            model.addAttribute("articleNumber", articleNumber);
            model.addAttribute("articleName",articleName);
        }
        return "search";
    }

    /**
     * 论坛主页
     */
    @GetMapping(value = "/forum")
    public String forum(){
        return "forum";
    }

    /**
     * 用户关注的功能
     */
    @PostMapping(value = "/user/concern")
    @ResponseBody
    public RespDTO addUserConcern(@RequestBody UserFriend userFriend){
        userFriendService.addUserConcern(userFriend);
        return RespDTO.ok("关注成功");
    }

    /**
     * 取消用户关注的功能
     */
    @DeleteMapping(value = "/user/cancelConcern/{userId}/{userFriendId}")
    @ResponseBody
    public RespDTO cancelUserConcern(@PathVariable("userId") Integer userId,
                                    @PathVariable("userFriendId") Integer userFriendId){
        HashMap<String,Integer> map = new HashMap<>();
        map.put("userId",userId);
        map.put("userFriendId",userFriendId);
        userFriendService.cancelUserConcern(map);
        return RespDTO.ok("取消关注成功");
    }

    /**
     * 个人信息修改页
     */
    @RequestMapping(value = "/settings")
    public String settings(Model model,HttpSession session){
        User userSession = (User)session.getAttribute("loginUser");
        User user = userService.findUserByUserId(userSession.getUserId());
        model.addAttribute("user",user);
     return "settings";
     }

     /**
     * 根据ID修改个人信息
     */
    @PutMapping(value = "/user/settings")
    @ResponseBody
    public RespDTO updateUserById(@RequestBody User user, HttpSession session) {
        User userSession = (User)session.getAttribute("loginUser");
        user.setUserId(userSession.getUserId());
        userService.updateUserByUser(user);
        return RespDTO.ok("修改成功");
    }

    /**
     * 修改密码页
     */
    @RequestMapping(value = "/settings/setpass")
    public String setPass(){
        return "setpass";
    }

    /**
     * 根据ID修改个人密码
     */
    @PostMapping({"/settings/password"})
    public String setPassword(@RequestParam("oldPassword") String oldPassword, @RequestParam("newPassword")
            String newPassword,@RequestParam("newPassword1") String newPassword1,
                              HttpSession session,Map<String,String> map) {
        User user = (User)session.getAttribute("loginUser");
        String password = BlogUtil.MD5(oldPassword + user.getUserSalt());

        if(user.getUserPassword().equals(password)) {
            if("".equals(newPassword)){
                map.put("msg", "请输入新密码");
            }else if(!newPassword.equals(newPassword1)){
                map.put("msg","两次输入的密码不一致");
            }
            else {
                user.setUserId(user.getUserId());
                user.setUserSalt(UUID.randomUUID().toString().substring(0, 5));
                user.setUserPassword(BlogUtil.MD5(newPassword + user.getUserSalt()));
                userService.updatePassword(user);
                map.put("msg1", "修改密码成功");
            }
        }else{
            map.put("msg","旧密码错误");
        }
        return "setpass";
    }

    /**
     * 个人头像图片上传
     * @param file
     * @return
     */
    @RequestMapping("/upload")
    public String uploadImage(@RequestParam("file") MultipartFile file, HttpSession session,Model model)
            throws IOException{
        // 保存图片的路径，图片上传成功后，将路径保存到数据库
        String filePath = "D:\\upload";
        User user = (User)session.getAttribute("loginUser");
        if (file.isEmpty()) {
            model.addAttribute("msg", "还没选择图片");
            model.addAttribute("user", user);
            return "settings";
        }
        // 获取原始图片的扩展名
        String originalFilename = file.getOriginalFilename();
        // 判断文件类型
        if(!"".equals(originalFilename) && originalFilename != null){
            // 生成文件新的名字
            String newFileName = UUID.randomUUID() + originalFilename;
            // 封装上传文件位置的全路径
            File targetFile = new File(filePath, newFileName);
            file.transferTo(targetFile);
            user.setUserId(user.getUserId());
            user.setUserProfilePhoto(url + newFileName);
            userService.updatePhoto(user);
            model.addAttribute("user", user);
            return "settings";
        }
        String msg = "请上传图片(格式为JPG、JPEG、PNG、GIF)";
        model.addAttribute("msg",msg);
        model.addAttribute("user",user);
        return "settings";
    }

    /**
     * 查询用户信息
     */
    @RequestMapping(value = "/person/{userId}")
    public String person(@PathVariable(value = "userId") Integer userId, Model model,
                         HttpSession session,@RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum){
        Integer concernNum = userFriendService.findConcernNum(userId);
        Integer fansNum = userFriendService.findFansNum(userId);
        Integer articleNum = articleService.findArticleNum(userId);
        Integer sortNum = articleService.findSortNum(userId);
        Integer collectNum = collectService.findCollectNumById(userId);
        PageHelper.startPage(pageNum,5);
        List<Article> articleList = articleService.findArticleByUserId(userId);
        PageInfo<Article> pageInfo = new PageInfo<Article>(articleList);
        List<UserFriend> concern = userFriendService.findUserConcern(userId);
        List<Category> category = articleService.findCategoryById(userId);
        User user = userService.findUserByUserId(userId);
        User userSession = (User)session.getAttribute("loginUser");
        List<UserFriend> concernSession = userFriendService.findUserConcern(userSession.getUserId());
        boolean b = false;
        for(UserFriend userFriend : concernSession){
            if(userFriend.getUser().getUserName().equals(user.getUserName())){
                b = true;
            }
        }
        model.addAttribute("concernNumber",concernNum);
        model.addAttribute("fansNumber",fansNum);
        model.addAttribute("articleNumber",articleNum);
        model.addAttribute("sortNumber",sortNum);
        model.addAttribute("collectNumber",collectNum);
        model.addAttribute("articleList",articleList);
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("concern",concern);
        model.addAttribute("category",category);
        model.addAttribute("user",user);
        model.addAttribute("b",b);
        return "person";
    }

    /**
     * 查询用户的粉丝
     */
    @RequestMapping(value = "/fans/{userId}")
    public String fans(@PathVariable(value = "userId") Integer userId,Model model,
                       HttpSession session,@RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum){
        Integer concernNum = userFriendService.findConcernNum(userId);
        Integer fansNum = userFriendService.findFansNum(userId);
        Integer articleNum = articleService.findArticleNum(userId);
        Integer sortNum = articleService.findSortNum(userId);
        Integer collectNum = collectService.findCollectNumById(userId);
        PageHelper.startPage(pageNum,5);
        List<Article> articleList = articleService.findArticleByUserId(userId);
        PageHelper.startPage(pageNum,5);
        List<UserFriend> fans = userFriendService.findUserFans(userId);
        PageInfo<UserFriend> pageInfo = new PageInfo<UserFriend>(fans);
        List<Category> category = articleService.findCategoryById(userId);
        User user = userService.findUserByUserId(userId);
        User userSession = (User)session.getAttribute("loginUser");
        List<UserFriend> concernSession = userFriendService.findUserConcern(userSession.getUserId());
        boolean b = false;
        for(UserFriend userFriend : concernSession){
            if(userFriend.getUser().getUserName().equals(user.getUserName())){
                b = true;
            }
        }
        model.addAttribute("concernNumber",concernNum);
        model.addAttribute("fansNumber",fansNum);
        model.addAttribute("articleNumber",articleNum);
        model.addAttribute("sortNumber",sortNum);
        model.addAttribute("collectNumber",collectNum);
        model.addAttribute("articleList",articleList);
        model.addAttribute("fans",fans);
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("category",category);
        model.addAttribute("user",user);
        model.addAttribute("b",b);
        return "fans";
    }

    /**
     * 查询已关注的用户
     */
    @RequestMapping(value = "/concern/{userId}")
    public String concern(@PathVariable(value = "userId") Integer userId,Model model,
                          HttpSession session,@RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum){
        Integer concernNum = userFriendService.findConcernNum(userId);
        Integer fansNum = userFriendService.findFansNum(userId);
        Integer articleNum = articleService.findArticleNum(userId);
        Integer sortNum = articleService.findSortNum(userId);
        Integer collectNum = collectService.findCollectNumById(userId);
        PageHelper.startPage(pageNum,5);
        List<Article> articleList = articleService.findArticleByUserId(userId);
        PageHelper.startPage(pageNum,5);
        List<UserFriend> concern = userFriendService.findUserConcern(userId);
        PageInfo<UserFriend> pageInfo = new PageInfo<UserFriend>(concern);
        List<Category> category = articleService.findCategoryById(userId);
        User user = userService.findUserByUserId(userId);
        User userSession = (User)session.getAttribute("loginUser");
        List<UserFriend> concernSession = userFriendService.findUserConcern(userSession.getUserId());
        boolean b = false;
        for(UserFriend userFriend : concernSession){
            if(userFriend.getUser().getUserName().equals(user.getUserName())){
                b = true;
            }
        }
        model.addAttribute("concernNumber",concernNum);
        model.addAttribute("fansNumber",fansNum);
        model.addAttribute("articleNumber",articleNum);
        model.addAttribute("sortNumber",sortNum);
        model.addAttribute("collectNumber",collectNum);
        model.addAttribute("articleList",articleList);
        model.addAttribute("concern",concern);
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("category",category);
        model.addAttribute("user",user);
        model.addAttribute("b",b);
        return "concern";
    }

    /**
     * 查询用户的某个分类的所有文章
     */
//    @GetMapping(value = "/article/category/{userId}/{sortId}")
//    public String findArticleBySortId(@PathVariable(value = "userId") Integer userId,
//                                      @PathVariable(value = "sortId") Integer sortId, Model model, HttpSession session,
//                                      @RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum){
    @GetMapping(value = "/article/category")
    public String findArticleBySortId(@RequestParam("userId") Integer userId,
                @RequestParam("sortId") Integer sortId, Model model, HttpSession session,
                @RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum){
        HashMap<String, Integer> map = new HashMap<String,Integer>();
        map.put("userId",userId);
        map.put("sortId",sortId);
        Integer concernNum = userFriendService.findConcernNum(userId);
        Integer fansNum = userFriendService.findFansNum(userId);
        Integer articleNum = articleService.findArticleNum(userId);
        Integer sortNum = articleService.findSortNum(userId);
        Integer collectNum = collectService.findCollectNumById(userId);
        PageHelper.startPage(pageNum,5);
        List<Article> articleList = articleService.findArticleByUserId(userId);
        List<Category> category = articleService.findCategoryById(userId);
        User user = userService.findUserByUserId(userId);

        PageHelper.startPage(pageNum,5);
        List<Article> articles = articleService.findArticle(map);
        PageInfo<Article> articleInfo = new PageInfo<Article>(articles);
        Integer articleSortNum = articleService.findArticleSortNum(map);

        User userSession = (User)session.getAttribute("loginUser");
        List<UserFriend> concernSession = userFriendService.findUserConcern(userSession.getUserId());
        boolean b = false;
        for(UserFriend userFriend : concernSession){
            if(userFriend.getUser().getUserName().equals(user.getUserName())){
                b = true;
            }
        }
        model.addAttribute("concernNumber",concernNum);
        model.addAttribute("fansNumber",fansNum);
        model.addAttribute("articleNumber",articleNum);
        model.addAttribute("sortNumber",sortNum);
        model.addAttribute("collectNumber",collectNum);
        model.addAttribute("articleList",articleList);
        model.addAttribute("category",category);
        model.addAttribute("user",user);
        model.addAttribute("articles",articles);
        model.addAttribute("articleInfo",articleInfo);
        model.addAttribute("articleSortNum",articleSortNum);
        model.addAttribute("b",b);
        model.addAttribute("sortId",sortId);
        return "category";
    }

    /**
     * 查询收藏文章信息
     */
    @RequestMapping(value = "/collect/{userId}")
    public String collect(@PathVariable(value = "userId") Integer userId, Model model,
                         HttpSession session,@RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum){
        Integer concernNum = userFriendService.findConcernNum(userId);
        Integer fansNum = userFriendService.findFansNum(userId);
        Integer articleNum = articleService.findArticleNum(userId);
        Integer sortNum = articleService.findSortNum(userId);
        Integer collectNum = collectService.findCollectNumById(userId);
        PageHelper.startPage(pageNum,5);
        List<Article> articleList = articleService.findArticleByUserId(userId);
        PageInfo<Article> pageInfo = new PageInfo<Article>(articleList);

        PageHelper.startPage(pageNum,5);
        List<Collect> collectList = collectService.findCollectByUserId(userId);
        PageInfo<Collect> collectInfo = new PageInfo<>(collectList);

        List<UserFriend> concern = userFriendService.findUserConcern(userId);
        List<Category> category = articleService.findCategoryById(userId);
        User user = userService.findUserByUserId(userId);
        User userSession = (User)session.getAttribute("loginUser");
        List<UserFriend> concernSession = userFriendService.findUserConcern(userSession.getUserId());
        boolean b = false;
        for(UserFriend userFriend : concernSession){
            if(userFriend.getUser().getUserName().equals(user.getUserName())){
                b = true;
            }
        }
        model.addAttribute("concernNumber",concernNum);
        model.addAttribute("fansNumber",fansNum);
        model.addAttribute("articleNumber",articleNum);
        model.addAttribute("sortNumber",sortNum);
        model.addAttribute("collectNumber",collectNum);
        model.addAttribute("articleList",articleList);
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("collectInfo",collectInfo);
        model.addAttribute("concern",concern);
        model.addAttribute("category",category);
        model.addAttribute("user",user);
        model.addAttribute("b",b);
        return "collect";
    }

}
